import $service from '../../../../../service.js';
var that;
var this_;
var doctor_id;
const app = getApp();
Page({
    data: {
        tipText: '',
        tipTitle: '',
        flag: true, //节流阀
        isShow: false, //弹窗控制
        canPay:true,    //支付控制
        "active": true,
        commentlist: [],
        doctorMap: {},
        isLoginshow: false,
        feeData: null,
        isFee: false,
        isOnline: 0, //医生在线状态
        isShowBrief: false,
        isShowSynopsis: false,
        index: 0, //选择状态的index
        ChooseServer: true, //医生是否选择了服务
        severList: [{
            icon: '/static/images/my_doctor/img_doctor@2x.png',
            noIcon: '/static/images/my_doctor/img_doctor_invalid@2x.png',
            name: '家庭医生',
            color: '#F47537',
            bgc: '#FFFCF8',
            type: 3,
            pirce: 0,
            index: 0,
            hasPayFee: false, //服务是否在问诊中
            IsCanPay: true, //是否置灰，false置灰
            explanation: [
                '为您提供全面的、连续的、有效的、及时的和个性化医疗保健服务和照顾，更合适慢病患者',
                '通过图文、文字咨询医生',
                '咨询期间未回复，50小时后自动退款',
                '医生根据情况提供建议、用药指导等，若重大疾病或紧急情况请及时前往医院就诊'
            ]
        }, {
            icon: '/static/images/my_doctor/img_consulting@2x.png  ',
            noIcon: '/static/images/my_doctor/img_consulting_invalid@2x.png',
            name: '复诊',
            color: '#1A99D5',
            bgc: '#F7FCFF',
            type: 4,
            pirce: 0,
            index: 1,
            hasPayFee: false, //服务是否在问诊中
            IsCanPay: true,
            explanation: [
                '顺利复诊、不折腾，更适合出院患者，非初诊患者及慢病患者',
                '通过图文、文字咨询医生',
                '咨询期间未回复，50小时后自动退款',
                '医生根据情况提供建议、用药指导等，若重大疾病或紧急情况请及时前往医院就诊',
            ]
        }, {
            icon: '/static/images/my_doctor/img_video@2x.png',
            noIcon: '/static/images/my_doctor/img_video_invalid@2x.png',
            name: '视频问诊',
            color: '#19A969',
            bgc: '#F8FFFC',
            type: 1,
            pirce: 0,
            index: 2,
            hasPayFee: false, //服务是否在问诊中
            IsCanPay: true,
            explanation: [
                '与医生面对面交流，沟通更方便，适合一般患者尤其是年长患者',
                '通过视频、文字在线咨询医生',
                '当天有效，若没有成功问诊，24小时后自动退款或主动在首页发起退款',
                '医生根据情况提供建议、用药指导等，若重大疾病或紧急情况请及时前往医院就诊'
            ]
        }, {
            icon: '/static/images/my_doctor/img_image@2x.png',
            noIcon: '/static/images/my_doctor/img_image_invalid@2x.png',
            name: '图文问诊',
            color: '#8472B5',
            bgc: '#FBFCFF',
            type: 2,
            pirce: 0,
            index: 3,
            hasPayFee: false, //服务是否在问诊中
            IsCanPay: true,
            explanation: [
                '医生立刻回复，耗时短，效率高，适合一般患者',
                '通过图文、文字在线咨询医生',
                '当天有效，若没有成功问诊，24小时后自动退款或主动在首页发起退款。',
                '医生根据情况提供建议、用药指导等，若重大疾病或紧急情况请及时前往医院就诊'
            ]
        }],
        bgc: '#FFFCF8',
        explainType: '家庭医生',
        explanationNum: 0,
        inquiryPrice: '',
        groups: [{
                text: '不再关注',
                type: 'warn',
                value: 0
            },
            {
                text: '仍然关注',
                value: 1
            }
        ],
        noFocus: false, // 显示关注弹窗
        // inquiryButtons: [{
        //     text: '知道了',              //显示文字
        //     extClass: 'knows-color'     //设置样式
        // }, {
        //     text: '进入聊天室',
        //     extClass: 'go-detial-color'
        // }], // 立即咨询弹窗
        // isShowInquiryDialog: false,
        isShowQR: false,
        doctorId: '',
        inquiryType: 3
    },
    onLoad(e) {
        doctor_id = e.doctorId;
        this.getAgreement()
        this.setData({
            doctorId: e.doctorId
        })
    },
    onShow() {
        that = this.data;
        this_ = this;
        this.getDoctorDetail();
        this.socketInit();
        this.getConsultationFee();
    },
    // 分享小程序
    onShareAppMessage(e) {
        const promise = new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    title: this.data.doctorMap.trueName + '医生的个人主页'
                })
            }, 1000)
        })
        return {
            title: this.data.doctorMap.trueName + '医生的个人主页',
            path: 'pages/user_side/index/index_doctorlist/index_doctor_details/index_doctor_details?doctorId=' + doctor_id,
            promise
        }
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.getDoctorDetail();
        this.getConsultationFee();
        setTimeout(() => {
            wx.stopPullDownRefresh();
        }, 1000)
    },
    socketInit() {
        app.webSocket.initWebSocket({
            url: $service.wsUrl
        })
        app.webSocket.onReceivedMsg(res => {
            if (res.packageType == 12) {
                this.getDoctorDetail();
            }
        })
    },
    // 获取问诊费订单
    getConsultationFee() {
        app.http.getConsultationFee({
            doctorId: doctor_id
        }).then(res => {
            console.log(res.data);
            if (res.data) {
                if (res.data.doctorId == doctor_id) {
                    switch (Number(res.data.inquiryType)) {
                        case 1:
                            this.data.severList[2].hasPayFee = true
                            break;
                        case 2:
                            this.data.severList[3].hasPayFee = true
                            break;
                        case 3:
                            this.data.severList[0].hasPayFee = true
                            break;
                        case 4:
                            this.data.severList[1].hasPayFee = true
                            break;
                        default:
                            break;
                    }
                }
            } else {
                this.data.severList.forEach(item => {item.hasPayFee = false})
            }
            this.setData({
                feeData: res.data,
                severList: this.data.severList
            })
        })
    },
    //获取各个问诊模块消息
    getDoctorDetail() {
        let params = {
            id: doctor_id,
            im: $service.getStore('userInfo') ? JSON.parse($service.getStore('userInfo')).id : ''
        }
        app.http.getDoctorDetail(params).then(res => {
            let doctorPackageInfoResps = this.serverSort(res.data.doctorPackageInfoResps)
            console.log(doctorPackageInfoResps)
            this.data.severList.forEach((item, index) => {
                item.enable = doctorPackageInfoResps[index].enable
                item.price = doctorPackageInfoResps[index].price / 100
                item.packageType = doctorPackageInfoResps[index].packageType
                //测试设置为图文
                // item.pirce = res.data.textInterrogation / 100;
                //判断按钮置灰
                if (res.data.isOnline == 0) {
                    //医生不在线时，将图文和视频置灰
                    item.enable == 0 ? item.IsCanPay = false : "";
                    index == 2 || index == 3 ? item.IsCanPay = false : ''
                } else {
                    if (res.data.inquiryType != 3) {
                        if (res.data.inquiryType == 2 && index == 2) {
                            item.IsCanPay = false;
                        } else if (res.data.inquiryType == 1 && index == 3) {
                            item.IsCanPay = false
                        }
                    }
                    item.enable == 0 ? item.IsCanPay = false : ""
                }
            })
            console.log(this.data.severList)
            let ChooseServer = this.data.severList.some((item, index) => {
                return item.enable == 1
            })
            let indexElement = this.data.severList.find((item) => {
                return item.IsCanPay == true;
            })
            console.log(indexElement);
            let index = 0;
            if (indexElement != undefined) {
                index = this.data.severList.find((item) => {
                    return item.IsCanPay == true;
                }).index
                this.setData({
                    index,
                    explanationNum: index
                })
            } 
            this.setData({
                doctorMap: res.data,
                isOnline: this.data.doctorMap.isOnline,
                severList: this.data.severList,
                //默认设置为家庭问诊价格
                inquiryPrice: this.data.severList[index].price,
                ChooseServer: ChooseServer
            })
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    tapactive(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 1) {
            this.data.active = true
        } else {
            this.data.active = false
        }
        this.setData({
            active: this.data.active
        })
    },
    gotopage(e) {
        wx.login({
            success(e) {
                console.log(e.code)
            }
        })
        $service.openPage('../../index_scheduling/index_scheduling?doctor_id=' + doctor_id)
    },
    //服务排序
    serverSort(arr) {
        let arr1 = arr.slice(2)
        let arr2 = arr.slice(0, 2)
        arr2.forEach(item => {
            arr1.push(item)
        })
        return arr1
    },
    // 简介展开/收起
    showBrief(e) {
        let {
            index
        } = e.currentTarget.dataset
        if (index === '1') {
            this.data.isShowBrief = !this.data.isShowBrief
        } else {
            this.data.isShowSynopsis = !this.data.isShowSynopsis
        }
        this.setData({
            isShowBrief: this.data.isShowBrief,
            isShowSynopsis: this.data.isShowSynopsis
        })
    },
    // 选择问诊方式
    changeServe(e) {
        let {
            index
        } = e.currentTarget.dataset
        let {
            bgc,
            name,
            IsCanPay,
            price,
        } = this.data.severList[index]
        if (IsCanPay) {
            this.setData({
                inquiryPrice: price,
                explanationNum: index,
                bgc,
                explainType: name,
                index
            })
        }
    },
    // 判断家庭医生是否超过48小时
    // exceeds48hours() {
    //     return app.http.exceeds48hours({doctorId: doctor_id}).then(res => {
    //         return res.data
    //     }).catch(err => {
    //         $service.showToast(err.msg)
    //     })
    // },
    concern() {
        if (this.data.doctorMap.isConcern == 1) {
            if (this.data.feeData) {
                if (this.data.feeData.inquiryType == 3) {
                    $service.showToast('当次问诊仍未结束，请结束后再尝试')
                }
            } else {
                this.setData({
                    noFocus: true
                })
            }
        } else {
            this.concernDoctor(1)
        }
    },
    // 关注医生
    concernDoctor(val) {
        let params = {
            "doctorId": Number(doctor_id),
            "isConcern": val
        }
        return app.http.concernDoctor(params).then(res => {
            $service.showToast('关注成功！')
            this.getDoctorDetail()
            return true
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },
   
    btnClick(e) {
        let {
            value
        } = e.detail
        if (value == 0) {
            this.concernDoctor(0)
        }
        this.setData({
            noFocus: false
        })
    },
    // 立即质询 1视频 2图文 3家庭医生 4复诊
    consult() {
        if (this.data.flag) {
            this.setData({
                flag: false,
            })
            if (this.data.feeData != null) {
                let {
                    inquiryType,
                    doctorId,
                    logId,
                    doctorIm,
                    inquiryPatientId,
                    userIm,
                    trueName,
                    id,
                } = this.data.feeData
                if (inquiryType == 3 || inquiryType == 4) { // 如果已经买了同一个医生的家庭医生、复诊
                    // this.data.inquiryButtons[1].text = inquiryType == 3 ? '家庭医生问诊' : '复诊问诊'
                    if (inquiryType == this.data.severList[this.data.index].type && doctorId == doctor_id) {
                        this.setData({
                            inquiryType: inquiryType,
                            // isShowInquiryDialog: true,
                            // inquiryButtons: this.data.inquiryButtons
                        })
                        if (logId) {
                            $service.openPage(`/pages/chat/user_chat/user_chat?logId=${logId}&imId=${doctorIm}&inquiryPatientId=${inquiryPatientId}&log_type=${inquiryType}&doctorId=${id}&doctorName=${trueName}&myIM=${userIm}`)
                        } else {
                            $service.openPage('/pages/user_side/inquiry_service/inquiry_write/inquiry_write?doctorId=' + doctor_id + '&log_type=' + inquiryType + '&doctorName=' + trueName)
                        }
                    } else {
                        let msg  = inquiryType == 3 ? "家庭问诊" : "复诊问诊"
                        this.showFamilyDocMoadal(msg)
                    }
                } else { // 如果买了图文、视频，进入的是进入医生的主页
                    if (inquiryType == this.data.severList[this.data.index].type && doctorId == doctor_id) {
                        this.setData({
                            isFee: true
                        })
                    } else {
                        let msg  = inquiryType == 1 ? "视频问诊" : "图文问诊"
                        this.showFamilyDocMoadal(msg)
                    }
                }
                return
            } else {
                this.setData({
                    isShow: !this.data.isShow
                })
            }
        }
        setTimeout(() => {
            this.setData({
                flag: true
            })
        }, 500)
    },
     // 家庭医生与复诊服务退款弹窗
     showFamilyDocMoadal(type) {
        wx.showModal({
            content: `您已购买${type}套餐，无须重复购买`,
            cancelText: '退款',
            confirmText: '取消',
            confirmColor: '#1189FF',
            success: (res) => {
                if (res.cancel) {
                    wx.showLoading({
                        title: "退款请求中",
                        mask: true
                    });
                    let params = {
                        "doctorId": this.data.feeData.doctorId,
                        "userId": JSON.parse($service.getStore('userInfo')).id,
                        "isFrozen": 0
                    }
                    app.http.refund(params).then(res => {
                        // 退款完成后调用问诊结束接口
                        this.data.feeData.logId ? this.endInquiry() : this.getConsultationFee();
                    }).catch(err => {
                        $service.showToast(err.msg);
                    }).finally(res => {
                        wx.hideLoading();
                    })
                }
                this.setData({
                    flag: true
                })
            },
        })
    },
    // 结束问诊
    endInquiry(){
        app.http.unSuccessfulInquiry({
            id: this.data.feeData.logId
        }).then(res => {
            wx.showToast({
                icon: "none",
                title: "退费成功",
                duration: 2000
              })
            this.getConsultationFee();
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    // 支付问诊费
    addConsultationFee() {
        wx.showLoading({
            title: "请求支付中",
            mask: true
        });
        let inquiry = this.data.severList[this.data.explanationNum].packageType
        wx.login({
            success: (res) => {
                let params = {
                    "code": res.code,
                    "doctorId": doctor_id,
                    'inquiryType': inquiry,
                    "totalFee": this.data.inquiryPrice * 100
                }
                console.log(params);
                app.http.addConsultationFee(params).then(res => {
                    let {
                        timeStamp,
                        nonceStr,
                        packageWx,
                        signType,
                        paySign
                    } = res.data
                    wx.requestPayment({
                        timeStamp,
                        nonceStr,
                        signType,
                        paySign,
                        'package': packageWx,
                        'success': (result) => {
                            if (result.errMsg == 'requestPayment:ok') {
                                if (inquiry == 1 || inquiry == 2) {
                                    $service.openPage('/pages/user_side/inquiry_service/inquiry_write/inquiry_write?doctorId=' + doctor_id + '&log_type=' + inquiry + '&doctorName=' + this.data.doctorMap.trueName)
                                } else {
                                    wx.requestSubscribeMessage({
                                        tmplIds: $service.userTmplIds,
                                        complete: (res) => {
                                            console.log(res);
                                            $service.openPage('/pages/user_side/inquiry_service/inquiry_write/inquiry_write?doctorId=' + doctor_id + '&log_type=' + inquiry + '&doctorName=' + this.data.doctorMap.trueName)
                                        },
                                        fail: (err) => {
                                            console.log(err);
                                        }
                                    })
                                }
                            }
                        },
                        'complete': (res) => {
                            wx.hideLoading();
                            this.setData({
                                canPay:true
                            })
                        }
                    })
                }).catch(err => {
                  this.setData({
                      canPay:true
                  })
                    $service.showToast(err.msg);
                })
            }
        })
    },
    // 分享医生二维码
    shareDoctor() {
        this.setData({
            isShowQR: true
        })
    },
    //首诊按钮
    firstVisit() {
        this.setData({
            isShow: !this.data.isShow
        })
    },
    //非首诊按钮
    async noFirstVisit() {
        if(this.data.canPay){
            this.setData({
                isShow: !this.data.isShow,
                canPay:false
            })
            let inquiry = this.data.severList[this.data.explanationNum].packageType
            if (inquiry == 1 || inquiry == 2) {
                this.addConsultationFee();
            } else {
                if (inquiry == 3) { // 如果是购买家庭医生套餐
                    if (this.data.doctorMap.isConcern == 0) { // 判断是否关注了医生
                        if (await this.concernDoctor(1)) {
                            this.addConsultationFee();
                        }
                    }
                    else{
                        this.addConsultationFee();
                    }
                }
                else{
                    this.addConsultationFee();
                }
            }
        }
    },
    // 获取患者须知
    getAgreement() {
      app.http.getAgreement({id: '7'}).then(res => {
        this.setData({
          tipText: res.data.initKey,
          tipTitle: res.data.initName
        })
      }).catch(err => {
        $service.showToast(err.msg)
      })
    }
})